<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    @register="registerDrawer"
    @close="onClose"
    width="95%"
  >
    <PageWrapper>
      <div class="main-content print-form">
        <div class="box box-main">
          <div class="table-fdiv">
            <a-form
              :model="record"
              ref="formRef"
              name="basic"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 16 }"
              autocomplete="off"
              @finish="onFinish"
              @finishFailed="onFinishFailed"
            >
              <table class="table-form">
                <tbody>
                  <tr>
                    <td class="form-label">版本号</td>
                    <td class="form-label">
                      <a-form-item name="verNum" :wrapper-col="{ offset: 0, span: 24 }">
                        <a-input v-model:value="record.verNum" />
                      </a-form-item>
                    </td>
                    <td class="form-label">备注</td>
                    <td colspan="2">
                      <a-form-item name="remarks" :wrapper-col="{ offset: 0, span: 24 }">
                        <a-textarea v-model:value="record.remarks" />
                      </a-form-item>
                    </td>
                  </tr>
                  <tr>
                    <td class="form-label">类型</td>
                    <td class="form-label">
                      <a-form-item name="ctype" :wrapper-col="{ offset: 0, span: 24 }">
                        <!-- <a-input v-model:value="record.ctype" /> -->
                        <a-select
                          v-model:value="record.ctype"
                          placeholder=""
                          :options="ctype_ref"
                          :field-names="{ label: 'dictLabel', value: 'dictValue' }"
                          :allowClear="true"
                        />
                      </a-form-item>
                    </td>
                  </tr>
                  <tr>
                    <td colspan="5"></td>
                  </tr>
                  <tr class="font-extrabold">
                    <td class="form-label" width="80">序号</td>
                    <td class="form-label">工位名称</td>
                    <td class="form-label">当前已采集工艺数据项</td>
                    <td class="form-label bg-green-100">设定值</td>
                    <td class="form-label">实际采集值</td>
                  </tr>
                  <tr v-for="(row, rowIndex) in formattedTableData" :key="rowIndex">
                    <td class="form-label">{{ row.sequence }}</td>
                    <!-- v-if="row.colspan>1" -->
                    <td class="form-label" :rowspan="row.rowspan" v-if="row.rowspan != 'rowspan'">{{
                      row.workstationName
                    }}</td>
                    <!-- <td>{{ row.dataItemName }}</td> -->
                    <td>
                      <a-form-item :name="row.tagname" no-style>
                        <a-input v-model:value="record.kstLsProCardDataCList[rowIndex].tagname" />
                      </a-form-item>
                    </td>
                    <td class="bg-green-100">
                      <a-form-item :name="row.itemName" no-style>
                        <a-input v-model:value="record.kstLsProCardDataCList[rowIndex].setVal" />
                      </a-form-item>
                    </td>
                    <td v-if="row.colspan === 1"></td>
                    <!-- 确保没有列合并时显示一个空单元格 -->
                  </tr>
                </tbody>
              </table>
              <div class="form-actions" v-if="showButton">
                <a-form-item :wrapper-col="{ offset: 2, span: 16 }">
                  <a-button type="primary" html-type="submit">提交</a-button>
                </a-form-item>
              </div>
            </a-form>
          </div>
        </div>
      </div>
    </PageWrapper>
    <template #footer></template>
  </BasicDrawer>
</template>
<script lang="ts">
  import { Form, Input, FormItem } from 'ant-design-vue';
  // import 'ant-design-vue/dist/reset.css';
  // 引入样式
  export default defineComponent({
    name: 'ViewsCardKstLsProCardDataHFormLS',
    components: {
      AForm: Form,
      AInput: Input,
      AFormItem: FormItem,
    },
  });
</script>
<script lang="ts" setup>
  import { defineComponent, reactive, ref, computed } from 'vue';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    KstLsProCardDataH,
    kstLsProCardDataHSave,
    kstLsProCardDataHForm,
  } from '/@/api/mes/card/kstLsProCardDataH';
  import { dictDataListData } from '/@/api/sys/dictData';
  const emit = defineEmits(['success', 'register']);

  const selectListRef = ref<Recordable[]>([]);

  const { showMessage } = useMessage();
  const listSelectRef = ref<any>(null);
  const showButton = ref(true);
  const ctype_ref = ref<any>(null);

  // const record = ref<KstMesProCardData>({} as KstMesProCardData);
  const record = ref<KstLsProCardDataH>({
    kstLsProCardDataCList: Array.from({ length: 32 }, (_, index) => ({
      id: index + 1,
      setVal: '',
    })),
  } as KstLsProCardDataH);
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    console.log('data==', data);
    showButton.value = true;
    setDrawerProps({ loading: true });
    const res = await kstLsProCardDataHForm(data);
    record.value = (res.kstLsProCardDataH || {}) as KstLsProCardDataH;
    console.log('record==', record);
    record.value.__t = new Date().getTime();
    record.value.ctype = data.ctype;
    record.value.verNum = data.verNum;
    if (data.isCopy) {
      record.value.code = '';
      record.value.id = '';
      record.value.isNewRecord = true;
      record.value.isCopy = false;
      record.value?.kstLsProCardDataCList?.forEach((item) => {
        item.id = '';
      });
    }
    // 如果record.value.kstLsProCardDataCList长度等于0，
    if (record.value.kstLsProCardDataCList.length == 0) {
      record.value.kstLsProCardDataCList = Array.from({ length: 32 }, (_, index) => ({
        id: index + 1,
        setVal: '',
      }));
    }
    ctype_ref.value = await dictDataListData({ dictType: 'mes_pro_type' });
    setDrawerProps({ loading: false });
  });
  const onFinish = async (values: any) => {
    try {
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        // code: record.value.code,
        id: record.value.id,
      };
      const res = await kstLsProCardDataHSave(params, record.value);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', values);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  const onClose = () => {
    closeDrawer();
    showButton.value = false;
  };

  const formattedTableData = computed(() => {
    console.log('record.value==', record);
    const data = record.value.kstLsProCardDataCList.map((item, index) => ({
      ...item,
      sequence: index + 1,
      workstationName: getWorkstationName(index),
      dataItemName: getDataItemName(item, index),
      itemName: getItemName(index),
      rowspan: getRowspan(index),
      colspan: getColspan(index),
    }));

    // 处理行跨度导致的空白单元格
    const result = [];
    let currentWorkstation = null;
    let currentRowspan = 1;

    data.forEach((row) => {
      if (row.workstationName !== currentWorkstation) {
        currentWorkstation = row.workstationName;
        currentRowspan = row.rowspan;
        result.push(row);
      } else {
        currentRowspan--;
        if (currentRowspan > 0) {
          result.push({
            ...row,
            setVal: '', // 空白行的设定值可以为空
            dataItemName: '', // 空白行的数据项名称可以为空
            itemName: '', // 空白行的表单项名称可以为空
            colspan: 4, // 空白行占据剩余的列
          });
        } else {
          result.push(row);
        }
      }
    });
    console.log('result==', result);
    return result;
  });

  const getRowspan = (index: number) => {
    // 根据索引返回适当的行跨度
    // 示例实现，需要根据实际情况调整
    const spans = {
      0: 3,
      3: 7,
      10: 4,
      14: 4,
      18: 4,
      22: 7,
      29: 2,
      31: 1,
    };
    return spans[index] || 'rowspan';
  };

  const getWorkstationName = (index: number) => {
    // 根据索引返回工作站名称
    // 示例实现，需要根据实际情况调整
    const names = {
      0: 'OP040',
      3: 'OP050',
      10: 'OP060',
      14: 'OP080',
      18: 'OP110',
      22: 'OP130',
      29: 'OP140-2',
      31: 'OP150',
    };
    return names[index] || '';
  };

  const getDataItemName = (item: any, index: number) => {
    // 根据索引返回数据项名称
    // 示例实现，需要根据实际情况调整
    // ...
    const names = {
      0: 'P10.基座条码',
      1: 'P10.打PIN位移',
      2: 'P10.把手型号代码',
      3: 'P20.1#螺丝扭矩',
      4: 'P20.2#螺丝扭矩',
      5: 'P20.3#螺丝扭矩',
      6: 'P20.4#螺丝扭矩',
      7: 'P20.5#螺丝扭矩',
      8: 'P20.基座条码',
      9: 'P20.把手型号代码',
      10: 'P30.右侧压入深度',
      11: 'P30.基座条码',
      12: 'P30.左侧压入深度',
      13: 'P30.把手型号代码',
      14: 'P40.压入力',
      15: 'P40.压入深度',
      16: 'P40.基座条码',
      17: 'P40.把手型号代码',
      18: 'P50.右侧压入力',
      19: 'P50.基座条码',
      20: 'P50.左侧压入力',
      21: 'P50.把手型号代码',
      22: 'P60.基座条码',
      23: 'P60.手柄电动弹出值',
      24: 'P60.把手型号代码',
      25: 'P60.把手堵转电流',
      26: 'P60.把手空载拉力值',
      27: 'P60.把手空载电流',
      28: 'P60.把手解锁行程',
      29: '间隙8个点位',
      30: '面差8个点位，漏装（NG/OK）',
      31: '总成分贝值（执行器不单独采集）',
    };
    return item.tagname ? item.tagname : names[index] || '';
  };

  const getItemName = () => {
    // 直接返回表单项的名称
    return 'setVal';
  };

  const getColspan = (index: number) => {
    // 根据索引返回列的跨度，通常为1，除非需要合并列
    return 1;
  };
</script>
<style scoped>
  :root {
    --global-font-size: 16px;
    /* 定义一个全局字体大小变量 */
  }

  .box-header {
    display: flex;
    justify-content: flex-end;
  }

  .table-fdiv {
    min-width: 600px;
    max-width: 100%;
    margin: 0 auto;
    font-size: var(--global-font-size);
  }

  .table-fdiv h3 {
    text-align: center;
    padding: 10px;
    font-size: 15px;
    font-weight: bold;
  }

  .table-fdiv table {
    width: 100%;
    font-size: var(--global-font-size);
  }

  .table-fdiv .form-actions {
    padding-left: 0 !important;
    padding: 15px 0;
    text-align: center;
    position: fixed;
    bottom: 0;
    z-index: 99999;
    right: 30px;
  }

  .table-form {
    border-collapse: collapse;
    border-spacing: 0;
  }

  .table-form td {
    padding: 6px;
    border: 1px solid #ddd;
    min-width: 30%;
    position: relative;
  }

  .table-form .form-title {
    background-color: #f5f5f5;
    color: #466172;
    font-weight: bold;
    height: 35px;
  }

  .table-form .form-label {
    position: static;
    text-align: center;
    padding: 13px;
    min-width: 20%;
  }

  .table-form .form-label .required {
    color: #e02222;
  }

  .table-form input,
  .table-form select,
  .table-form textarea,
  .table-form .form-control,
  .table-form .select2-selection {
    border: 0;
    background-color: transparent;
    resize: none;
    box-shadow: none;
    border-radius: 0;
  }

  .table-form .form-control:focus,
  .table-form .select2-container--default.select2-container--focus .select2-selection--single,
  .table-form .select2-container--default.select2-container--focus .select2-selection--multiple {
    border: 0;
    border-bottom: 1px dotted #cdcdcd !important;
    box-shadow: none;
  }

  .table-form .select2-container .select2-selection--single .select2-selection__rendered {
    margin-top: -3px;
  }

  .table-form .form-control[readonly]:focus {
    border-bottom: 0 !important;
  }

  .table-form .input-group-btn > .btn {
    border: 0;
    background: transparent;
    box-shadow: none;
    color: #888;
  }

  .table-form .input-group-btn > .btn {
    height: 20px;
    padding: 0 6px 0 7px;
  }

  .table-form .icheck label {
    line-height: 28px;
  }

  .table-form .ui-jqgrid td {
    padding: 0;
    border: 0;
  }

  .table-form .ui-jqgrid tr.ui-row-ltr td input,
  .table-form .ui-jqgrid tr.ui-row-ltr td select,
  .table-form .ui-jqgrid tr.ui-row-ltr td textarea,
  .table-form .ui-jqgrid tr.ui-state-highlight.ui-row-ltr td,
  .table-form .ui-jqgrid tr.ui-state-highlight.ui-row-ltr td input,
  .table-form .ui-jqgrid tr.ui-state-highlight.ui-row-ltr td select,
  .table-form .ui-jqgrid tr.ui-state-highlight.ui-row-ltr td textarea,
  .table-form .ui-jqgrid tr.ui-row-ltr.ui-priority-secondary td input,
  .table-form .ui-jqgrid tr.ui-row-ltr.ui-priority-secondary td select,
  .table-form .ui-jqgrid tr.ui-row-ltr.ui-priority-secondary td textarea,
  .table-form .ui-jqgrid tr.ui-state-highlight.ui-row-ltr.ui-priority-secondary td,
  .table-form .ui-jqgrid tr.ui-state-highlight.ui-row-ltr.ui-priority-secondary td input,
  .table-form .ui-jqgrid tr.ui-state-highlight.ui-row-ltr.ui-priority-secondary td select,
  .table-form .ui-jqgrid tr.ui-state-highlight.ui-row-ltr.ui-priority-secondary td textarea {
    background-color: transparent !important;
  }

  .table-form .ui-jqgrid tr.ui-state-highlight {
    background-color: #f6fbff !important;
  }

  .ant-form-item {
    margin-bottom: 0 !important;
  }

  .ant-input {
    border: 1px solid #ddd !important;
  }
</style>
